//
//  RGFocusVedioListView.m
//  RedGrass
//
//  Created by wukong on 2019/1/27.
//  Copyright © 2019年 hongcaosp. All rights reserved.
//

#import "RGFocusVedioListView.h"
#import "RGMeDynamicsCell.h"
#import <MJRefresh.h>
#import "GKDYVideoPlayer.h"

#define  itemBaseTag  100000

@interface RGFocusVedioListView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,GKDYVideoPlayerDelegate>

@property (nonatomic, strong) UICollectionView                 *collectionView;
@property (nonatomic, strong) NSMutableArray *focusList;
@property (strong, nonatomic) MJRefreshNormalHeader *freshHeader;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *freshFooter;
@property (strong, nonatomic) GKDYVideoPlayer *vedioPlayer;
//@property (assign, nonatomic) NSInteger  itemIndex;
@property (assign, nonatomic) NSIndexPath *playingPath;


@end

@implementation RGFocusVedioListView

-(instancetype) initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
//        _itemIndex = itemBaseTag;
        [self addSubview:self.collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
    }
    return self;
}

//UICollectionViewDataSource Delegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_focusList count];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if([_focusList count]){
        RGRecommendVideoModel *model = _focusList[indexPath.row];
        return CGSizeMake(KScreenWidth, model.cellHeight);
    }
    return  CGSizeMake(KScreenWidth, 0);
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RGMeDynamicsCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RGMeDynamicsCell" forIndexPath:indexPath];
    cell.tag = itemBaseTag + indexPath.row;
    if([_focusList count]){
        RGRecommendVideoModel *model = _focusList[indexPath.row];
        cell.vedioModel = model;
        AA_WEAK_MAKE(self)weakSelf = self;
        [cell setActionBtnClickBlock:^(NSInteger tag) {
            if(tag == kFocusListFocusTag){//点赞
                if([weakSelf.viewDelegate respondsToSelector:@selector(favoriteVedioWithView:chosedIndexPath:)]){
                    [weakSelf.viewDelegate favoriteVedioWithView:weakSelf chosedIndexPath:indexPath];
                }
            }else if (tag == kFocusListCommentTag){//评论
                if([weakSelf.viewDelegate respondsToSelector:@selector(comementVedioWithView:chosedIndexPath:)]){
                    [weakSelf.viewDelegate comementVedioWithView:weakSelf chosedIndexPath:indexPath];
                }
            }else if (tag == kFocusListShareTag){//g转发
                if([weakSelf.viewDelegate respondsToSelector:@selector(shareVedioWithView:chosedIndexPath:)]){
                    [weakSelf.viewDelegate shareVedioWithView:weakSelf chosedIndexPath:indexPath];
                }
            }else if (tag == kFocusListPlayBtnTag){//点击了播放按钮
                [weakSelf updateCellVedioPlayStatusWithIndexPath:indexPath];
            }
        }];
    }
    return cell;
  
}

//UICollectionViewDelegate Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - public

-(void) reloadCollectionViewWithList:(NSMutableArray *)focusList{
    if(focusList == nil){
        return;
    }
    _focusList = focusList;
    [_collectionView reloadData];
    [self.collectionView.mj_footer endRefreshing];
}

-(void) setFocusViewMjFooterStatusWithNoMoreData{
     [self.collectionView.mj_footer endRefreshingWithNoMoreData];
//    _freshFooter.state = MJRefreshStateNoMoreData;
}

-(void) focusViewMjHeaderLoadingEnd{
    [_freshHeader endRefreshing];
}

-(void) focusViewMjFooterLoadingEnd{
    [_freshFooter endRefreshing];
}

-(void) changeFarvoriteStatusWithIndexPath:(NSIndexPath *)path{
    if(path.row >= _focusList.count){
        return;
    }
    
    [_collectionView reloadItemsAtIndexPaths:[NSArray arrayWithObjects:path,nil]];
}

-(void) stopPlayingWhenCurrentVCIsNoteVisiable{
    if([_vedioPlayer isPlaying]){
        [_vedioPlayer pausePlay];
    }
}

-(void)playVideo:(NSIndexPath *)path {
    if(self.playingPath) {
        RGMeDynamicsCell *oldCell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:self.playingPath];
        oldCell.isShowPlayBtn = NO;
    }
    self.playingPath = path;
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:path];
//    self.itemIndex = cell.tag;
    [self.vedioPlayer removeVideo];
    [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
    if([self.viewDelegate respondsToSelector:@selector(updateVedioPlayCountWithCellIndex:)]){
        [self.viewDelegate updateVedioPlayCountWithCellIndex:cell.tag-itemBaseTag];
    }
}

-(void) playVedioWithFirstIndexWhenLoadSuccess{
//    _itemIndex = 0;
//     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//     });
    dispatch_async(dispatch_get_main_queue(), ^{
        //刷新完成
        [self playVideo:[NSIndexPath indexPathForRow:0 inSection:0]];
    });
    
//    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//    self.itemIndex = cell.tag;
//    [self.vedioPlayer removeVideo];
//    [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
//    if([self.viewDelegate respondsToSelector:@selector(updateVedioPlayCountWithCellIndex:)]){
//        [self.viewDelegate updateVedioPlayCountWithCellIndex:cell.tag-itemBaseTag];
//    }
}

-(void) startFavoriteAnimationWithIsFavorite:(BOOL)isFavorite cellIndex:(NSInteger)index{
      RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    [cell updateFaroviteStauts];
}


-(void)updateCommentCountsWhenCommentSuccessWithCellIndex:(NSInteger)cellIndex{
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:cellIndex inSection:0]];
    [cell updateCommentCounts];
}

-(void)updateforwardCountsWhenShareSuccessWithCellIndex:(NSInteger)cellIndex{
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:cellIndex inSection:0]];
    [cell updateForwardCounts];
}

#pragma mark -response

-(void)loadFocus{
    if([self.viewDelegate respondsToSelector:@selector(loadFocusVedioListWithView:isLoadMore:)]){
        [self.viewDelegate loadFocusVedioListWithView:self isLoadMore:NO];
    }
}

-(void)loadMoreFocus{
    if([self.viewDelegate respondsToSelector:@selector(loadFocusVedioListWithView:isLoadMore:)]){
        [self.viewDelegate loadFocusVedioListWithView:self isLoadMore:YES];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 将collectionView在控制器view的中心点转化成collectionView上的坐标
    CGPoint pInView = [self convertPoint:self.collectionView.center toView:self.collectionView];
    NSIndexPath *path = [_collectionView indexPathForItemAtPoint:pInView];
//    RGMeDynamicsCell  *cell = (RGMeDynamicsCell *)[_collectionView cellForItemAtIndexPath:path];
    
    if([path isEqual:self.playingPath]){//表示是当前
        
    }else{
//        _itemIndex = cell.tag;
        [self playVideo:path];
//        [_vedioPlayer removeVideo];
//        [self.vedioPlayer playVideoWithView:cell.vedioGroudView url:cell.vedioUrl];
//        if([self.viewDelegate respondsToSelector:@selector(updateVedioPlayCountWithCellIndex:)]){
//            [self.viewDelegate updateVedioPlayCountWithCellIndex:cell.tag-itemBaseTag];
//        }
    }
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSArray<NSIndexPath *> *visiblePaths = [self.collectionView indexPathsForVisibleItems];
    if (visiblePaths.count > 0) {
        for (NSIndexPath *path in visiblePaths) {
            if ([path isEqual:_playingPath]) {
                return;
            }
        }
    }
    if ([self.vedioPlayer isPlaying]) {
        [_vedioPlayer removeVideo];
    }
}

//更新当前cell的视频播放状态
-(void) updateCellVedioPlayStatusWithIndexPath:(NSIndexPath *)path{
    if(![path isEqual:self.playingPath]){//点击的不是当前的播放视频的cell
        [self playVideo:path];
        return;
    }
    if(_vedioPlayer.status == GKDYVideoPlayerStatusPlaying){
        [_vedioPlayer pausePlay];
    
    }else if (_vedioPlayer.status == GKDYVideoPlayerStatusPaused){
        [_vedioPlayer resumePlay];
    }
}

- (void)player:(GKDYVideoPlayer *)player statusChanged:(GKDYVideoPlayerStatus)status{
//    NSInteger index = _itemIndex - itemBaseTag;
//    if(index < 0){
//        return;
//    }
    if (!_playingPath) {
        return;
    }
    RGMeDynamicsCell *cell = (RGMeDynamicsCell *)[self.collectionView cellForItemAtIndexPath:_playingPath];
    if(_vedioPlayer.status == GKDYVideoPlayerStatusPlaying){
        cell.isShowPlayBtn = YES;
    }else if (_vedioPlayer.status == GKDYVideoPlayerStatusPaused){
        cell.isShowPlayBtn = NO;
    } else if (_vedioPlayer.status == GKDYVideoPlayerStatusLoading) {
        cell.loading = YES;
    }
}


#pragma mark - getter

-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10;
//        flowLayout.estimatedItemSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width, 200);
        _collectionView = [[UICollectionView  alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
//            _collectionView.automaticallyAdjustsScrollViewInsets = NO;
        }
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[RGMeDynamicsCell class] forCellWithReuseIdentifier:@"RGMeDynamicsCell"];
        _collectionView.mj_header = self.freshHeader;
        _collectionView.mj_footer = self.freshFooter;
        
    }
    return _collectionView;
}

-(MJRefreshNormalHeader *)freshHeader{
    if(!_freshHeader){
        _freshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadFocus)];
       
    }
    return _freshHeader;
}

-(MJRefreshAutoNormalFooter *)freshFooter{
    if(!_freshFooter){
        _freshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFocus)];
        [_freshFooter setTitle:@"暂时没有更多了" forState:MJRefreshStateNoMoreData];
    }
    return _freshFooter;
}

-(GKDYVideoPlayer *)vedioPlayer{
    if(!_vedioPlayer){
        _vedioPlayer = [[GKDYVideoPlayer alloc]init];
        _vedioPlayer.renderMode = RENDER_MODE_FILL_SCREEN;
        _vedioPlayer.delegate = self;
    }
    return _vedioPlayer;
}


@end
